package com.gitee.faster.webdav.common.structure;

import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.text.StrPool;
import com.gitee.faster.webdav.common.constant.Constants;

/**
 * 对应请求头 Range 的值
 *
 * @author hongda.li
 */
public record RangeValue(long start, long end, String origin) {

    /**
     * 根据 RANGE 请求头里面的值和文件大小动态计算需要读写的范围
     *
     * @param rangeHeader 原始请求头的值
     * @param totalSize   文件总大小
     * @return 读写范围
     */
    public static RangeValue from(String rangeHeader, long totalSize) {
        if (CharSequenceUtil.isBlank(rangeHeader)) {
            return null;
        }

        if (!CharSequenceUtil.containsAny(rangeHeader, Constants.BYTES + Constants.EQUALS, StrPool.DASHED)) {
            return null;
        }

        String[] split = rangeHeader.substring(rangeHeader.lastIndexOf(Constants.EQUALS) + 1)
                .trim()
                .split(StrPool.DASHED);

        // N-""
        if (split.length == 1) {
            return new RangeValue(Long.parseLong(split[0]), totalSize - 1, rangeHeader);
        }

        // ""-M
        if (CharSequenceUtil.isEmpty(split[0])) {
            long end = Long.parseLong(split[1]);
            return new RangeValue(0, end, rangeHeader);
        }

        // N-M
        long start = Long.parseLong(split[0]);
        long end = Long.parseLong(split[1]);
        return new RangeValue(start, end, rangeHeader);
    }

    @Override
    public String toString() {
        return this.origin;
    }
}
